Option Explicit On 
Option Strict On

Imports TreeCreeper01Interfaces

Friend Class cSpeciesListAnalysis
    Implements ISpeciesListAnalysis


    Private pSpeciesList As ISpeciesAbundanceList


    Public Sub New(ByVal SpeciesList As ISpeciesAbundanceList)
        pSpeciesList = SpeciesList
    End Sub


    ' BASE LOGIC:
    ' iterate each leaf node against all other nodes
    ' sum the distances and divide by number of nodepairs
    '
    ' ACTUAL IMPLEMENTATION:
    ' Instead of n*n calculations we can manage with only (n*n)/2 calculations
    Public Function CalculateGenericNonSpatialDiversity() As Double Implements ISpeciesListAnalysis.CalculateGenericNonSpatialTaxonomicDiversity

        Dim TotalDiversity As Double

        Dim CumulativeDiversityValue As Double
        Dim CumulativeSeparatePairsCount As Integer

        Dim SpeciesCount As Integer
        Dim CurrentStartSpeciesIndex As Integer
        Dim CurrentEndSpeciesIndex As Integer
        Dim CurrentStartSpecies As ITaxonomicSpecies
        Dim CurrentEndSpecies As ITaxonomicSpecies
        Dim CurrentNodeDistance As Single

        'Debug.WriteLine("Starting calculation of generic non spatial diversity")

        SpeciesCount = pSpeciesList.CountOfSpecies

        For CurrentStartSpeciesIndex = 1 To SpeciesCount

            'Debug.WriteLine("calculating generic non spatial diversity for leaf node " & CurrentStartSpeciesIndex)

            CurrentStartSpecies = pSpeciesList.SpeciesByIndexBaseOne(CurrentStartSpeciesIndex).TaxonomicSpecies

            For CurrentEndSpeciesIndex = CurrentStartSpeciesIndex + 1 To SpeciesCount
                CurrentEndSpecies = pSpeciesList.SpeciesByIndexBaseOne(CurrentEndSpeciesIndex).TaxonomicSpecies

                CurrentNodeDistance = pSpeciesList.TaxonomicDistanceProvider.TaxonomicDistanceBetweenSpecies(CurrentStartSpecies, CurrentEndSpecies)

                If CurrentNodeDistance > 0 Then
                    CumulativeSeparatePairsCount += 1
                    CumulativeDiversityValue += CurrentNodeDistance
                End If

            Next
        Next


        If CumulativeSeparatePairsCount = 0 Then
            TotalDiversity = 0
        Else
            TotalDiversity = CumulativeDiversityValue / CumulativeSeparatePairsCount
        End If

        'Debug.WriteLine("Ending calculation of generic non spatial diversity")

        Return TotalDiversity

    End Function

End Class
